package com.ruoyi.web.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.config.wx.WxPayConfiguration;
import com.ruoyi.common.core.domain.ApiResult;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IGoodsService;
import com.ruoyi.system.service.IShopActivityService;
import com.ruoyi.system.service.IShopNoticeService;
import com.ruoyi.system.service.IShopOrderService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 微信回调函数Controller
 */
@Api(description = "微信回调函数")
@Controller
@RequestMapping("/api/weixin/notify")
public class ApiWeiXinNotifyController {

    @Autowired
    IShopNoticeService shopNoticeService;

    @Autowired
    IShopOrderService shopOrderService;

    @Autowired
    IGoodsService goodsService;

    @Autowired
    IShopActivityService shopActivityService;

    public static Object lock = new Object();
    //回调pay通知
    @RequestMapping("/pay")
    public String pay(@RequestBody String xmlData) {
        WxPayService wxPayService = WxPayConfiguration.wxService();
        try {
            final WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);

            String orderSn = notifyResult.getOutTradeNo();
            synchronized (lock){
                // 业务处理
                ShopOrder order = shopOrderService.selectShopOrderBySn(orderSn);
                if (order.getStatus() != ShopOrder.Status.pendingPayment.ordinal()){
                    order.setStatus(Long.valueOf(ShopOrder.Status.shipped.ordinal()));
                    order.setAmountPaid(order.getAmount());

                    //生成code 用于核销
                    String code = RandomStringUtils.random(8, "abcdefghijklmnopqrstuvwxyz1234567890");

                    //TODO:查找这个code 是否被使用过 建立code表用数据库保持唯一，订单数量级上来可以更换。
                    order.setCode(code);



                    //减少库存
                    List<ShopOrderItem> orderItems = order.getShopOrderItems();
                    for(ShopOrderItem shopOrderItem : orderItems){
                        Long goodsId = shopOrderItem.getGoodsId();
                        Goods goods = goodsService.selectGoodsById(goodsId);
                        if (goods == null || goods.getIsMarketable() == false){
                            //TODO： 发生了异常
                        }
                        goods.setSales(goods.getSales() + shopOrderItem.getQuantity());
                        //TODO:减少库存 //判断活动逻辑
                        if (goods.getStock() < shopOrderItem.getQuantity()){
                            //要退款了。 没有商品了
                            order.setStatus(Long.valueOf(ShopOrder.Status.refunding.ordinal()));
                            shopOrderService.updateShopOrder(order);
                        }else{
                            goods.setStock(goods.getStock() - shopOrderItem.getQuantity());
                        }
                        goodsService.updateGoods(goods);
                        shopOrderService.updateShopOrder(order);
                    }
                }
                return WxPayNotifyResponse.success("成功");
            }
        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return WxPayNotifyResponse.success("失败");
    }
}
